package com.wtwd.campus.controller;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.dao.CustomerMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.service.*;
import com.wtwd.campus.utils.*;
import com.wtwd.campus.vcom.service.VcomFenceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2022/02/24
 * @description
 */
@Api(tags = "测试")
@RestController
@RequestMapping("/test")
public class TestController {


    @Autowired
    private RedisService redisService;

    @Autowired
    private CommandSendUtils commandSendUtils;

    @Autowired
    private LocationService locationService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private VcomFenceService vcomFenceService;

    @Autowired
    private FenceInfoService fenceInfoService;

    @Resource
    private PolygonFenceService polygonFenceService;

    @Resource
    private CustomerMapper customerMapper;

    @ApiOperation("获取设备缓存命令集")
    @GetMapping("/test/{imei}")
    public Map getTest(@PathVariable String imei) {
        String key = Constants.COMMAND_PREFIX + imei;
        Map<String, Object> hash = redisService.getCommandsByImei(imei);
        return hash;
    }

    @ApiOperation("查询设备是否在线")
    @GetMapping("/deviceOnline/{imei}")
    public Boolean getDeviceOnline(@PathVariable String imei) {
        boolean online = commandSendUtils.deviceOnline(imei);
        return online;
    }

    @ApiOperation("查询设备在线总数")
    @GetMapping("/getDeviceOnlineNum")
    public int getDeviceOnlineNum(@RequestHeader("accessToken") String accessToken) {
        System.out.println(accessToken);
        List valuesByLikePrefix = redisService.getValuesByLikePrefix(Constants.DEVICE_ONLINE_PREFIX);
        return valuesByLikePrefix.size();
    }

    /**
     * 此处接口用于查询围栏中心点的距离
     * 根据设备获取定位点信息(此处接口只用于查找问题，如果正式如要，请重新编写)
     */
    @ApiOperation("此处接口用于查询围栏中心点的距离")
    @PostMapping("/getDistance")
    public RespEntity getDistance(@RequestBody TestVo testVo) {
        DeviceInfo device = deviceInfoService.getDeviceByImei(testVo.getImei());
        List<LocationData> locationDatas = locationService.getLocationByTime(device.getDeviceId(), 1676259257000L, 1678678457000L);
        List<Integer> fenceInfos = testVo.getFenceInfos();
        ArrayList<Map> maps = new ArrayList<>();
        if (fenceInfos != null && fenceInfos.size() > 0) {
            for (Integer fenceId : fenceInfos) {
//                VcomCircleFence vcomCircleFence = vcomFenceService.getVcomFenceInfoByFenceId(fenceId);
//                List<FenceInfo> vcomCircleFence = fenceInfoService.getFenceInfoListByStuId(device.getStudentId());
//                FenceInfo vcomCircleFence = fenceInfoService.getFenceInfoById(fenceId);
                List<CustomerFence> deviceFenceList = customerMapper.getDeviceFenceList(testVo.getImei());
                CustomerFence customerFenceList = deviceFenceList.get(0);
                if (customerFenceList != null) {
                    for (LocationData locationData : locationDatas) {
                        double locationLgn = Double.parseDouble(locationData.getLongitude());
                        double locationLat = Double.parseDouble(locationData.getLatitude());
                        double distance = GPSUtils.getDistance(locationLgn, locationLat, Double.parseDouble(customerFenceList.getLongitude()), Double.parseDouble(customerFenceList.getLatitude()));
                        Map<String, Object> map = new HashMap<>();
                        map.put("fenceId", customerFenceList.getId());
                        map.put("locationLgn", locationLgn);
                        map.put("locationLat", locationLat);
                        map.put("distance", distance);
                        map.put("time", DateUtils.format(new Date(locationData.getLocationTime()), DateUtils.dateFormat4));
                        map.put("redis", customerFenceList.getRadius());
                        maps.add(map);
                    }
                }
            }
        }
        return new RespEntity(RespCode.SUCCESS, maps);
    }

    /**
     *
     */
    @ApiOperation("获取多边形围栏是否进出定位点")
    @PostMapping("/getPolygonFenceDistance")
    public RespEntity getPolygonFenceDistance(@RequestBody TestVo testVo) {
        DeviceInfo device = deviceInfoService.getDeviceByImei(testVo.getImei());
        PolygonFence polygonFence = polygonFenceService.getOrgPolygonFenceByDeviceTypeAndCustomerIdAndFenceId(Constants.VCOM_DEVICE, 1, "38721340fb904b3695a2d756d401f85b");
        //获取该设备的定位数据
        List<LocationData> locationDatas = locationService.getLocationByTime(device.getDeviceId(), 1669087800000L, 1669093800000L);
        ArrayList<Map> maps = new ArrayList<>();
        String jsonPoints = polygonFence.getFencePoints();
        if (locationDatas != null && locationDatas.size() > 0) {
            for (LocationData locationData : locationDatas) {
                List<FencePoints> fencePoints = JSONObject.parseArray(jsonPoints, FencePoints.class);
                Double[] fenceLongitude = fencePoints.stream().map(FencePoints::getLongitude)
                        .collect(Collectors.toList()).toArray(new Double[fencePoints.size()]);
                Double[] fenceLatitude = fencePoints.stream().map(FencePoints::getLatitude)
                        .collect(Collectors.toList()).toArray(new Double[fencePoints.size()]);
                double lastLgn = Double.parseDouble(locationData.getLongitude());
                double lastLat = Double.parseDouble(locationData.getLatitude());
                boolean lastLocationPoint = RegionUtil.isPolygonContainsPoint(fenceLongitude, fenceLatitude, fencePoints.size(), lastLgn, lastLat);
                double[] doubles = GPSUtils.gps84_To_Gcj02(lastLat, lastLgn);
                Map<String, Object> map = new HashMap<>();
                map.put("fenceId", polygonFence.getFenceId());
                map.put("locationLgn", doubles[1]);
                map.put("locationLat", doubles[0]);
                map.put("type", locationData.getLocationType());
                map.put("rest", lastLocationPoint);
                map.put("time", DateUtils.format(new Date(locationData.getLocationTime()), DateUtils.dateFormat4));
                maps.add(map);
            }
        }
        return new RespEntity(RespCode.SUCCESS, maps);
    }

    @ApiOperation("获取设备轨迹")
    @GetMapping("/getDeviceLocation/{imei}")
    public RespEntity getDeviceLocation(@PathVariable("imei") String imei) {
        DeviceInfo device = deviceInfoService.getDeviceByImei(imei);
        ArrayList<Map> list = new ArrayList<>();
        if (device != null) {
//            List<LocationData> locationData = locationService.getLocationByDeviceId(device.getDeviceId());
            List<LocationData> locationData = locationService.getLocationByTime(device.getDeviceId(), 1669564800000L, 1669601653000L);
            locationData.stream().forEach(e ->
            {
                HashMap<String, Object> map = new HashMap<>();
                map.put("imei", e.getDeviceImei());
                map.put("locationType", e.getLocationType());
                map.put("address", e.getAddress());
                map.put("lat", e.getLatitude());
                map.put("lon", e.getLongitude());
                map.put("time", DateUtils.format(new Date(e.getLocationTime()), DateUtils.dateFormat4));
                list.add(map);
            });
        }
        return new RespEntity(RespCode.SUCCESS, list);
    }

    /**
     * 此处接口用于用于模拟添加设备
     * 用于模拟tcp并发测试，并不对外开放
     *
     * @param
     */
    @ApiOperation("批量添加设备号")
    @PostMapping("/testBathAddDevice")
    public RespEntity testBathAddDevice(@RequestBody TestBathAddDeviceDto testBathAddDeviceDto) {
        String starImei = testBathAddDeviceDto.getStarImei();
        List<DeviceInfo> deviceInfos = new ArrayList<>();
        for (Integer i = 0; i < testBathAddDeviceDto.getLength(); i++) {
            //记录可以成功添加的设备
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setImei(String.valueOf(Integer.valueOf(starImei) + i));
            deviceInfo.setModel("cs");
            deviceInfo.setDeviceType(testBathAddDeviceDto.getDeviceType());
            deviceInfo.setCustomerId(testBathAddDeviceDto.getCustomerId());
            deviceInfo.setCreateTime(new Date().getTime());
            deviceInfo.setUpdateTime(new Date().getTime());
            deviceInfo.setIfScreen(0);
            deviceInfos.add(deviceInfo);
        }
        deviceInfoService.bathAddDeviceInfo(deviceInfos);
        return new RespEntity(RespCode.SUCCESS);
    }


    /**
     * 同步设备锁网
     *
     * @param mqGetLockNet
     * @return
     */
    @ApiOperation("同步锁网")
    @PostMapping("/synchronizationLockNet")
    public RespEntity synchronizationLockNet(@RequestBody MqGetLockNet mqGetLockNet) {
        commandSendUtils.getLockNet(mqGetLockNet, true, 1, false);
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 同步锁卡
     *
     * @param mqGetLockCard
     * @return
     */
    @ApiOperation("同步锁卡")
    @PostMapping("/synchronizationLockCard")
    public RespEntity synchronizationLockNet(@RequestBody MqGetLockCard mqGetLockCard) {
        commandSendUtils.getLockCard(mqGetLockCard, true, 1, false);
        return new RespEntity(RespCode.SUCCESS);
    }

    @ApiOperation("同步锁机")
    @PostMapping("/synchronizationLockDevice")
    public RespEntity synchronizationLockDevice(@RequestBody MqGetLockDevice mqGetLockDevice) {
        commandSendUtils.getLockDevice(mqGetLockDevice, true, 1, false);
        return new RespEntity(RespCode.SUCCESS);
    }

    @PostMapping("/fileTest")
    public RespEntity addProblemFeedback(@RequestParam(value = "files") MultipartFile[] files, HttpServletResponse response) throws Exception {
        List<ExcelImportTest> allList = new ArrayList<>();
        for (MultipartFile file : files) {
            List<ExcelImportTest> excelImportTests = MyExcelUtils.importExcel(file, 0, 1, ExcelImportTest.class);
            allList.addAll(excelImportTests);
        }
        String path = MyExcelUtils.exportExcel(allList, "订单信息", "订单信息", ExcelImportTest.class, "订单信息.xls", response);
        return new RespEntity(RespCode.SUCCESS, path);
    }

    @ApiOperation("tg")
    @GetMapping("/tg")
    public RespEntity tg(HttpServletResponse response) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        long threeYearsInMillis = 3 * 365 * 24 * 60 * 60 * 1000;  // 三年的毫秒数
//        List<DeviceInfo> deviceInfos = deviceInfoService.getDeviceByAll();
////        deviceInfos = deviceInfos.stream().filter(e -> e.getCreateTime() + threeYearsInMillis < new Date().getTime()).collect(Collectors.toList());
          //以下是excel统计
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        List<DeviceInfo> deviceInfos = deviceInfoService.getDeviceByAll();
//        deviceInfos=deviceInfos.stream().filter(e->e.getDeviceType()==5).collect(Collectors.toList());
//        for (DeviceInfo deviceInfo : deviceInfos) {
//            deviceInfo.setCreateTimeStr(sdf.format(new Date(deviceInfo.getCreateTime())));
//            if (deviceInfo.getDeviceType() == 1) {
//                deviceInfo.setName(deviceInfo.getOrgName());
//            }
//            if (deviceInfo.getDeviceType() == 2) {//云对接设备
//                if (deviceInfo.getCustomerId() == 4) {
//                    deviceInfo.setName("四川启迪");
//                }
//                if (deviceInfo.getCustomerId() == 5) {
//                    deviceInfo.setName("和校园");
//                }
//                if (deviceInfo.getCustomerId() == 6) {
//                    deviceInfo.setName("艾威比特");
//                }
//                if (deviceInfo.getCustomerId() == 7) {
//                    deviceInfo.setName("家家晓");
//                }
//                if (deviceInfo.getCustomerId() == 8) {
//                    deviceInfo.setName("家家晓");
//                }
//                if (deviceInfo.getCustomerId() == 9) {
//                    deviceInfo.setName("长虹健康");
//                }
//                if (deviceInfo.getCustomerId() == 10) {
//                    deviceInfo.setName("长虹健康");
//                }
//            }
//            if (deviceInfo.getDeviceType() == 3) {//h5设备
//                if (deviceInfo.getCustomerId() == null || deviceInfo.getCustomerId() == 10) {
//                    deviceInfo.setName("沃特校园H5");
//                } else if (deviceInfo.getCustomerId() == 1) {
//                    deviceInfo.setName("威科姆");
//                } else if (deviceInfo.getCustomerId() == 3) {
//                    deviceInfo.setName("正指向四川");
//                } else if (deviceInfo.getCustomerId() == 4) {
//                    deviceInfo.setName("正指向宁夏和教育");
//                } else if (deviceInfo.getCustomerId() == 5) {
//                    deviceInfo.setName("瑞翼湖南和教育");
//                } else if (deviceInfo.getCustomerId() == 6) {
//                    deviceInfo.setName("正指向湖南和教育");
//                } else if (deviceInfo.getCustomerId() == 7) {
//                    deviceInfo.setName("壹教");
//                } else if (deviceInfo.getCustomerId() == 8) {
//                    deviceInfo.setName("湖南和教育长虹");
//                } else if (deviceInfo.getCustomerId() == 11) {
//                    deviceInfo.setName("福建瑞翼E15");
//                } else if (deviceInfo.getCustomerId() == 12) {
//                    deviceInfo.setName("湖北电信瑞翼E15");
//                } else if (deviceInfo.getCustomerId() == 13) {
//                    deviceInfo.setName("小湃");
//                } else if (deviceInfo.getCustomerId() == 14) {
//                    deviceInfo.setName("湖南长沙和教育");
//                } else if (deviceInfo.getCustomerId() == 15) {
//                    deviceInfo.setName("雷纹");
//                }
//            }
//            if (deviceInfo.getDeviceType() == 4) {//和校园设备
//                deviceInfo.setName("和校园设备");
//            }
//            if (deviceInfo.getDeviceType() == 5) {//威科姆设备
//                deviceInfo.setName("威科姆");
//            }
//            if (StringUtils.isBlank(deviceInfo.getName())){
//                deviceInfo.setName("总部测试设备");
//            }
//
//        }
//        String path = MyExcelUtils.exportExcel(deviceInfos, "设备导入", "订单信息", DeviceInfo.class, "设备导入.xls", response);
//        return new RespEntity(RespCode.SUCCESS, path);
        return null;
    }


    public static void main(String[] args) {
        // 东八区的时间戳
        long timestamp = 1718662294807L;

        // 将时间戳转换为东八区的本地时间
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zoneIdBeijing = ZoneId.of("Asia/Shanghai");
        ZonedDateTime beijingTime = instant.atZone(zoneIdBeijing);

        // 格式化输出东八区时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedBeijingTime = beijingTime.format(formatter);
        System.out.println("东八区时间: " + formattedBeijingTime);

        // 将东八区时间转换为印度时间
        ZoneId zoneIdIndia = ZoneId.of("Asia/Kolkata");
        ZonedDateTime indiaTime = beijingTime.withZoneSameInstant(zoneIdIndia);

        // 格式化输出印度时间
        String formattedIndiaTime = indiaTime.format(formatter);
        System.out.println("印度时间: " + formattedIndiaTime);
    }


    public static int test() {
        try {
            int a = 1 / 0;
            return 1;
        } catch (Exception e) {
            System.out.println("出现异常");
        }
        return 0;
    }


}

